package com.onpositive.wiki2.miner;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.onpositive.wiki3.db.LocationProperties;

public class WikiPediaPass {

	public static void doPass(final AbstractWikiPediaVisitor v){
		try {
			File f = new File(LocationProperties.getProperty(LocationProperties.LOCATION_WIKI_DUMP));
			SAXParserFactory.newInstance().newSAXParser().parse(f, new DefaultHandler(){
				
				Page page;
				StringBuilder bld=new StringBuilder();
				
				@Override
				public void startElement(String uri, String localName,
						String qName, Attributes attributes)
				{
					bld.delete(0,bld.length());
					if (qName.equals("page")){
						page=new Page();
					}
				}
				
				@Override
				public void endElement(String uri, String localName,
						String qName) throws SAXException {
					localName=qName;
					if (localName.equals("title")){
						page.title=bld.toString();
					}
					if (localName.equals("id")){
						if (page.id==-1){
							page.id=Long.parseLong(bld.toString());
						}
					}
					if (localName.equals("text")){
						page.textContent=bld.toString();
						v.onPage(page);
					}
					super.endElement(uri, localName, qName);
				}
				@Override
				public void ignorableWhitespace(char[] ch, int start, int length)
						throws SAXException {
					bld.append(ch, start, length);
					super.ignorableWhitespace(ch, start, length);
				}
				
				@Override
				public void characters(char[] ch, int start, int length)
						throws SAXException {
					bld.append(ch, start, length);					
				}
				
			});
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
